package com.angel.controller;

import com.angel.bean.Employee;
import com.angel.bean.InMessage;
import com.angel.bean.dto.SocketEmployeeDto;
import com.angel.service.OtherlogService;
import com.angel.service.WebSocketService;
import com.angel.socket.WebSocketUrl;
import com.angel.socket.WebSocketUsers;
import com.angel.utils.AdminUserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class WsController {
    @Autowired
    WebSocketService webSocketService;
    @Autowired
    private OtherlogService otherlogService;


    @MessageMapping(WebSocketUrl.FORETOSERVERPATH)//@MessageMapping和@RequestMapping功能类似，用于设置URL映射地址，浏览器向服务器发起请求，需要通过该地址。
    @SendTo(WebSocketUrl.PRODUCERPATH)//如果服务器接受到了消息，就会对订阅了@SendTo括号中的地址传送消息。
    public InMessage say(InMessage message) throws Exception {
//       List<String> users = new ArrayList();
//        users.add("d892bf12bf7d11e793b69c5c8e6f60fb");//此处写死只是为了方便测试,此值需要对应页面中订阅个人消息的userId
        //    webSocketService.send2Users(users, new InMessage("admin hello"));

        return new InMessage("Welcome, " + message.getFrom() + "!");
    }


    /**
     * 单对单发送
     *
     * @param message
     */
    @MessageMapping(WebSocketUrl.TOEMPMAS)
    public void sndToEmp(InMessage message) {
        webSocketService.sendToEmp(message);
    }


    @RequestMapping("/test")
    public String test() {
        return "test";
    }


    @RequestMapping("/getallemp")
    @ResponseBody
    public Object getOnlineeMP(@RequestParam("type") String type) {
        System.out.println(type);
        Map<String, SocketEmployeeDto> map = WebSocketUsers.getEmap();
        Map re = new HashMap();
        List<SocketEmployeeDto> employees = new ArrayList<>();
        List<SocketEmployeeDto> allemployees = new ArrayList<>();
        Employee employee = AdminUserUtils.getPrincipal().getEmployee();
        if (type != null && type.length() > 0) {
            for (String key : map.keySet()) {
                SocketEmployeeDto tmp = map.get(key);
                if (tmp.getTypeName().equals(type) && tmp.getBranchesId().equals(employee.getBranchesId())) {
                    employees.add(tmp);
                }
                allemployees.add(tmp);
                System.out.println("Key: " + key);
            }
        }
        re.put("emp", employees);
        re.put("test", allemployees);
        return re;
    }

}
